import { getData } from '~/server/plugins/getData'

// 定义接口返回的数据类型
interface MainCategoryItem {
  name: string
  displayName: string
  subCategoryCount: number
  appCount: number
  description: string
}

interface ApiResponse {
  success: boolean
  message: string
  data: MainCategoryItem[]
  total: number
  dataSource?: string
  error?: string
}

export default defineEventHandler(async (event): Promise<ApiResponse> => {
  try {
    const { getCurrentRequestData, getDataSourceData } = getData()
    
    // 获取查询参数
    const query = getQuery(event)
    const dataSource = query.dataSource as string // 可选参数，指定数据源
    
    // 使用插件提供的数据
    let categoryData: any = null
    
    if (dataSource) {
      // 如果指定了数据源，使用指定的数据源
      categoryData = getDataSourceData(dataSource)
      
      if (!categoryData) {
        return {
          success: false,
          message: `指定的数据源 "${dataSource}" 不存在`,
          data: [],
          total: 0,
          dataSource
        }
      }
    } else {
      // 否则使用当前域名的数据
      const currentData = getCurrentRequestData(event)
      
      if (currentData) {
        categoryData = currentData.data
      }
    }
    
    if (!categoryData) {
      return {
        success: false,
        message: '无法获取分类数据，请检查域名配置或数据源设置',
        data: [],
        total: 0
      }
    }
    
    // 验证数据结构
    if (!Array.isArray(categoryData.mainCategories) || 
        !categoryData.subCategories || 
        !categoryData.categoryData) {
      return {
        success: false,
        message: '数据格式错误，缺少必要的分类数据结构',
        data: [],
        total: 0
      }
    }
    
    // 构建一级分类列表，包含统计信息
    const mainCategories: MainCategoryItem[] = categoryData.mainCategories.map((category: string) => {
      const subCategoryCount = categoryData.subCategories[category]?.length || 0
      const appCount = Object.values(categoryData.categoryData[category] || {}).reduce((total: number, apps: any) => {
        return total + (Array.isArray(apps) ? apps.length : 0)
      }, 0)
      
      return {
        name: category,
        displayName: category,
        subCategoryCount,
        appCount,
        description: `包含 ${subCategoryCount} 个二级分类，总计 ${appCount} 个应用`
      }
    })
    
    return {
      success: true,
      message: '获取一级分类列表成功',
      data: mainCategories,
      total: mainCategories.length,
      dataSource: dataSource || 'current'
    }
    
  } catch (error: any) {
    console.error('获取一级分类列表错误:', error)
    return {
      success: false,
      message: '获取一级分类列表过程中发生错误',
      data: [],
      total: 0,
      error: process.env.NODE_ENV === 'development' ? error?.message : undefined
    }
  }
}) 